import { Injectable } from "@angular/core";
import { RbacPermModel } from "../module/rbac/rbac-perm.model";
import { UserModel } from "../module/user/user.model";

@Injectable()
export class CoreService {
	private userModel: UserModel = new UserModel;
	private permCodeMap: any = {};

	setUserModel(userModel: UserModel): void {
		this.userModel = userModel;
		let permMap: Map<number, RbacPermModel> = new Map();
		var permData: Array<RbacPermModel> = [];
		if (userModel.rbacRoleBO && userModel.rbacRoleBO.rbacPermBOList) {
			for (let permModel of userModel.rbacRoleBO.rbacPermBOList) {
				permModel.children = [];
				permMap.set(permModel.id, permModel);
				if (permModel.type == 1) {
					permData.push(permModel);
				}
				if (permModel.type == 3) {
					this.permCodeMap[permModel.code] = true;
				}
			};
			for (let permModel of userModel.rbacRoleBO.rbacPermBOList) {
				if(permModel.type == 2){
					let parentPermModel = permMap.get(permModel.parentId);
					if (parentPermModel) {
						parentPermModel.children.push(permModel);
					}
				}
			};
		}
		userModel.rbacPermList = permData;
		this.userModel = userModel;
	}

	getPermCodeMap() {
		return this.permCodeMap;
	}

	hasPerm(permCode: string) {
		return this.permCodeMap[permCode];
	}

	getUserModel(): UserModel {
		return this.userModel;
	}

	//加法计算,小数位数不足补充0
	add(num1: number, num2: number) {
		const num1Digits = (num1.toString().split('.')[1] || '').length;
		const num2Digits = (num2.toString().split('.')[1] || '').length;
		let maxLength = Math.max(num1Digits, num2Digits)
		const baseNum = Math.pow(10, maxLength);
		let result = ((parseFloat((num1 * baseNum).toFixed()) + parseFloat((num2 * baseNum).toFixed())) / baseNum).toFixed(maxLength);
		return result;
	}
	dateFormat(time: Date) {
		if (time instanceof Date) {
			return `${time.getFullYear()}/${time.getMonth() + 1}/${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getHours()}`
		} else {
			return time
		}
	}

	getToken(){
		return sessionStorage.getItem("ADMIN_JWT_NAME");
	}
	
	setToken(token:string){
		sessionStorage.setItem("ADMIN_JWT_NAME",token);
	}

	clearToken(){
		sessionStorage.removeItem("ADMIN_JWT_NAME");
	}

}
